import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import '../../../common/service/HttpService.dart';

class ForgetController extends GetxController {
  // 手机号
  final TextEditingController phoneController = TextEditingController();

  // 手机号验证码
  final TextEditingController phoneCodeController = TextEditingController();

  // 新密码 & 确认密码
  final TextEditingController newPasswordController = TextEditingController();
  final TextEditingController confirmNewPasswordController = TextEditingController();

  // 获取手机验证码按钮文本
  final RxString getPhoneCode = "获取手机验证码".obs;

  // 倒计时
  final RxInt countdown = 0.obs;

  bool get isCounting => countdown.value > 0;

  // 手机号验证状态
  final RxBool phoneVerify = false.obs;

  bool get isPhoneVerify => phoneVerify.value;

  Timer? _timer;

  @override
  void onReady() {
    super.onReady();
    update(["forget"]);

    // 监听倒计时变化，自动更新按钮文字
    ever(countdown, (_) {
      getPhoneCode.value = isCounting ? "${countdown.value}s后重发" : "获取手机验证码";
    });
  }

  @override
  void onClose() {
    _timer?.cancel();
    phoneController.dispose();
    phoneCodeController.dispose();
    newPasswordController.dispose();
    confirmNewPasswordController.dispose();
    super.onClose();
  }

  /// 校验手机号
  bool _validatePhone(String phone) {
    if (phone.isEmpty || phone.length != 11) {
      EasyLoading.showError("手机号不足11位");
      return false;
    }
    return true;
  }

  /// 发送验证码
  Future<void> sendPhoneCode() async {
    final phone = phoneController.text.trim();
    if (!_validatePhone(phone)) return;

    try {
      final response = await HttpService.to.get("/user/sendPhoneCode", query: {"phoneNumber": phone});
      if (response.statusCode == 200 && response.data["code"] == 200) {
        startCountdown(60);
        EasyLoading.showSuccess("发送验证码成功");
      } else {
        EasyLoading.showError(response.data["msg"] ?? "发送失败");
      }
    } catch (e) {
      EasyLoading.showError("发送手机验证码异常");
      debugPrint("发送手机验证码异常: $e");
    }
  }

  /// 启动倒计时
  void startCountdown(int seconds) {
    _timer?.cancel();
    countdown.value = seconds;

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countdown.value--;
      if (countdown.value <= 0) {
        timer.cancel();
      }
    });
  }

  /// 验证手机号 + 验证码
  Future<void> phoneCodeVerify() async {
    final phone = phoneController.text.trim();
    final phoneCode = phoneCodeController.text.trim();

    if (!_validatePhone(phone)) return;
    if (phoneCode.isEmpty || phoneCode.length != 6) {
      EasyLoading.showError("手机验证码不足6位");
      return;
    }

    try {
      final response = await HttpService.to.post("/user/phone/login", data: {"phoneNumber": phone, "phoneCode": phoneCode});

      if (response.statusCode == 200 && response.data["code"] == 200) {
        phoneVerify.value = true;
        EasyLoading.showSuccess("手机号验证成功");
      } else {
        EasyLoading.showError(response.data["msg"] ?? "验证失败");
      }
    } catch (e) {
      EasyLoading.showError("手机号校验异常");
      debugPrint("手机号校验异常: $e");
    }
  }

  /// 重置密码
  Future<void> forget() async {
    final phone = phoneController.text.trim();
    final newPassword = newPasswordController.text.trim();
    final confirmNewPassword = confirmNewPasswordController.text.trim();

    if (newPassword.length < 6 || confirmNewPassword.length < 6) {
      EasyLoading.showError("新密码不能少于6位数");
      return;
    }
    if (newPassword != confirmNewPassword) {
      EasyLoading.showError("两次输入的密码不一致");
      return;
    }

    try {
      final response = await HttpService.to.get("/user/forget/password", query: {"phoneNumber": phone, "password": newPassword});

      if (response.statusCode == 200 && response.data["code"] == 200) {
        EasyLoading.showSuccess("修改密码成功");
        Get.back();
      } else {
        EasyLoading.showError(response.data["msg"] ?? "修改失败");
      }
    } catch (e) {
      EasyLoading.showError("修改密码异常");
      debugPrint("修改密码异常: $e");
    }
  }
}
